<template>
	<div id="newConfig">
		<div class="breadcrumb">
			<img src="../../../../static/img/outClass_icon_1.png" class="head_img">
			<span class="title" @click="cancel()">运动管理</span>
			<span>/ 编辑运动设置</span>
		</div>

		<div class="list">
			<div class="list_head">
				<span class="head_name">运动设置信息</span>
				<el-button class="save" type="primary" @click="save()">保存</el-button>
				<el-button class="cancel" type="primary" @click="cancel()">返回</el-button>
			</div>
			<el-form ref="configForm" :model="configForm" :rules="rules" label-width="150px">
				<el-form-item label="设置校区:" prop="campusZone" required>
					<el-select v-model="configForm.campusZone" class="el-select" disabled>
						<el-option label='全部校区' value='0'></el-option>
						<el-option v-for='item in campusZones' :label='item.name' :value='item.unid' :key='item.unid'>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="每日计入成绩上限:" prop="maleDayUpper">
					<el-input type="number" v-model="configForm.maleDayUpper" class="el-input1"></el-input>公里（男）
				</el-form-item>
				<el-form-item label="单次跑步最低要求:" prop="maleMinSingleDis">
					<el-input type="number" v-model="configForm.maleMinSingleDis" class="el-input1"></el-input>公里（男）
				</el-form-item>
				<el-form-item label="每日计入成绩上限:" prop="femaleDayUpper">
					<el-input type="number" v-model="configForm.femaleDayUpper" class="el-input1"></el-input>公里（女）
				</el-form-item>
				<el-form-item label="单次跑步最低要求:" prop="femaleMinSingleDis">
					<el-input type="number" v-model="configForm.femaleMinSingleDis" class="el-input1"></el-input>公里（女）
				</el-form-item>
				<el-form-item label="跑步配速:" required>
					<el-form-item class="peisu" prop="speedLimit_min">
						<el-input type="number" v-model="configForm.speedLimit_min" style="margin-right:5px;" required>
						</el-input>
					</el-form-item>
					<el-form-item class="peisu" prop="speedLimit_minSec">
						<el-input type="number" v-model="configForm.speedLimit_minSec" style="margin-right:5px;">
						</el-input>
					</el-form-item>
					<span style="margin-left:5px;margin-right:5px;"></span>
					至
					<el-form-item class="peisu" prop="speedLimit_max">
						<el-input type="number" v-model="configForm.speedLimit_max"
							style="margin-left:10px;margin-right:5px;"></el-input>
					</el-form-item>
					<span style="margin-left:10px;"></span>
					<el-form-item class="peisu" prop="speedLimit_maxSec">
						<el-input type="number" v-model="configForm.speedLimit_maxSec" style="margin-right:5px;">
						</el-input>
					</el-form-item>
					<span style="margin-left:5px;margin-right:5px;">（分钟/公里）</span>
					<span style="margin-left:5px;margin-right:5px;color:red;">* 请在2~10分钟内设置跑步配速</span>
				</el-form-item>
				<el-form-item label="点位顺序跑:" prop="sequenceRun">
					<el-switch v-model="sequenceRun" on-text="" off-text=""></el-switch>
				</el-form-item>
				<el-form-item label="开启自由跑计算成绩:" prop="isFreedomRunCalculate">
					<el-switch v-model="isFreedomRunCalculate" on-text="" off-text=""></el-switch>
				</el-form-item>
				<el-form-item label="跑步有效时间:" prop="effectiveTime">
					<el-switch v-model="effectiveTime" on-text="" off-text=""></el-switch>
					<div v-show="effectiveTime" style="margin-top:15px;">
						<el-time-picker v-model="time1" format="HH:mm"
							:picker-options="{selectableRange: '00:00:00 - 23:59:59'}" placeholder="开始时间点">
						</el-time-picker>
						至
						<el-time-picker v-model="time2" format="HH:mm"
							:picker-options="{selectableRange: '00:00:00 - 23:59:59'}" placeholder="结束时间点">
						</el-time-picker>
						<el-button type="primary" @click="handleAddTime()">确定</el-button>
					</div>
					<div v-show="effectiveTime" class="effect-time-tag">
						<el-tag :key="tag" v-for="tag in timeTags" :closable="true"
							style="margin:0 5px;height:auto;font-size:14px;" :close-transition="false"
							@close="handleClose(tag)">
							{{tag}}
						</el-tag>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<el-dialog title="公告提示" :visible.sync="dialogFormVisible_save">
			<div>是否发布自动公告提示学生规则变更？</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="publishHandle(0)">保存</el-button>
				<el-button type="primary" @click="publishHandle(1)">保存并发布</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { mapState, mapActions } from "vuex";

	export default {
		data() {
			let checkMin = (rule, value, callback) => {
				if (value) {
					let minSec = this.configForm.speedLimit_minSec * 1,
						max = this.configForm.speedLimit_max * 1,
						maxSec = this.configForm.speedLimit_maxSec * 1;
					if (value * 1 > this.configForm.speedLimit_max * 1) {
						callback(new Error("请正确填写跑步配速"));
					} else {
						if (value * 1 < 2 || value * 1 > 10) {
							callback(new Error("请在2~10min内设置跑步配速"));
						} else {
							if (minSec > 0 && value * 1 == 10) {
								callback(new Error("请在2~10min内设置跑步配速"));
							}
							if (minSec > maxSec && value * 1 == max) {
								callback(new Error("请正确填写跑步配速"));
							}
							callback();
						}
					}
				} else {
					callback();
				}
			};
			let checkMax = (rule, value, callback) => {
				if (value) {
					if (this.configForm.speedLimit_min * 1 > value * 1) {
						callback(new Error("请正确填写跑步配速"));
					} else {
						if (value * 1 < 2 || value * 1 > 10) {
							callback(new Error("请在2~10min内设置跑步配速"));
						} else {
							let minSec = this.configForm.speedLimit_minSec * 1,
								min = this.configForm.speedLimit_min * 1,
								maxSec = this.configForm.speedLimit_maxSec * 1;
							if (value * 1 == 10 && maxSec > 0) {
								callback(new Error("请在2~10min内设置跑步配速"));
							}
							if (value * 1 == min && minSec > maxSec) {
								callback(new Error("请正确填写跑步配速"));
							}
							callback();
						}
					}
				} else {
					callback();
				}
			};

			let checkSecmin = (rule, value, callback) => {
				if (value) {
					if (value * 1 < 0 || value * 1 >= 60) {
						callback(new Error("请正确填写跑步配速"));
					} else {
						let min = this.configForm.speedLimit_min * 1,
							max = this.configForm.speedLimit_max * 1,
							maxSec = this.configForm.speedLimit_maxSec * 1;
						if (min == 10 && value * 1 > 0) {
							callback(new Error("请在2~10min内设置跑步配速"));
						}
						if (min == max && value * 1 > maxSec) {
							callback(new Error("请正确填写跑步配速"));
						}
						callback();
					}
				} else {
					callback();
				}
			};

			let checkSecmax = (rule, value, callback) => {
				if (value) {
					if (value * 1 < 0 || value * 1 >= 60) {
						callback(new Error("请正确填写跑步配速"));
					} else {
						let min = this.configForm.speedLimit_min * 1,
							max = this.configForm.speedLimit_max * 1,
							minSec = this.configForm.speedLimit_minSec * 1;
						if (max == 10 && value * 1 > 0) {
							callback(new Error("请在2~10min内设置跑步配速"));
						}
						if (min == max && value * 1 < minSec) {
							callback(new Error("请正确填写跑步配速"));
						}
						callback();
					}
				} else {
					callback();
				}
			};

			let checkMaleRunLength = (rule, value, callback) => {
				if (value) {
					if (value * 1 <= 0) {
						callback(new Error('请正确填写跑步公里数'))
					} else {
						let max = this.configForm.maleDayUpper;
						if (value > max) {
							callback(new Error('单次跑步最低要求，不能高于每日计入成绩上线'))
						} else {
							callback();
						}
					}
				} else {
					callback();
				}
			};

			let checkFemaleRunLength = (rule, value, callback) => {
				if (value) {
					if (value * 1 <= 0) {
						callback(new Error('请正确填写跑步公里数'))
					} else {
						let max = this.configForm.femaleDayUpper;
						if (value > max) {
							callback(new Error('单次跑步最低要求，不能高于每日计入成绩上线'))
						} else {
							callback();
						}
					}
				} else {
					callback();
				}
			};

			return {
				unid: "",
				time1: "",
				time2: "",
				timeTags: [],
				publishAnno: 0,
				campusZones: [],
				sequenceRun: false,
				isFreedomRunCalculate: false,
				randomValidTime: [],
				effectiveTime: false,
				dialogFormVisible_save: false,
				configForm: {
					maleDayUpper: "2",
					maleMinSingleDis: "1",
					femaleDayUpper: "2",
					femaleMinSingleDis: "1",
					speedLimit_min: "2",
					speedLimit_max: "10",
					speedLimit_minSec: "00",
					speedLimit_maxSec: "00",
					campusZone: ""
				},
				rules: {
					maleDayUpper: [
						{ required: true, message: "每日计入成绩上限不能为空", trigger: "blur" }
					],
					maleMinSingleDis: [
						{ required: true, message: "单次跑步最低要求不能为空", trigger: "blur" },
						{ validator: checkMaleRunLength }
					],
					femaleDayUpper: [
						{ required: true, message: "每日计入成绩上限不能为空", trigger: "blur" }
					],
					femaleMinSingleDis: [
						{ required: true, message: "单次跑步最低要求不能为空", trigger: "blur" },
						{ validator: checkFemaleRunLength }
					],
					speedLimit_min: [
						{ required: true, message: "跑步配速不能为空", trigger: "blur" },
						{ validator: checkMin }
					],
					speedLimit_max: [
						{ required: true, message: "跑步配速不能为空", trigger: "blur" },
						{ validator: checkMax }
					],
					speedLimit_minSec: [
						{ required: true, message: "跑步配速不能为空", trigger: "blur" },
						{ validator: checkSecmin }
					],
					speedLimit_maxSec: [
						{ required: true, message: "跑步配速不能为空", trigger: "blur" },
						{ validator: checkSecmax }
					]
				}
			};
		},
		mounted() {
			this.unid = this.$util.getUrlParam("unid");
			this.getCampus();
			this.getConfigDetail();
		},
		watch: {
			effectiveTime: function (val) {
				if (val == false) {
					this.timeTags = [];
					this.randomValidTime = [];
				}
			}
		},
		computed: mapState({ user: state => state.user }),
		methods: {
			//保存配置
			save() {
				this.$refs.configForm.validate(valid => {
					if (valid) {
						this.dialogFormVisible_save = true;
					}
				});
			},
			publishHandle(num) {
				this.dialogFormVisible_save = false;
				let url = this.$util.domain + "/managerapi/v1/sportconfig/save";
				let speedLimit_st = (this.configForm.speedLimit_min * 1 + this.configForm.speedLimit_minSec / 60).toFixed(2);
				let speedLimit_et = (this.configForm.speedLimit_max * 1 + this.configForm.speedLimit_maxSec / 60).toFixed(2);

				this.$http({
					url,
					method: "POST",
					credentials: true,
					body: JSON.stringify({
						publishAnno: num,
						unids: this.unid + "",
						unid: parseInt(this.unid),
						rootUnid: this.user.rootUnid * 1,
						isSequence: this.sequenceRun ? 1 : 0,
						isFreedomRunCalculate: this.isFreedomRunCalculate ? 1 : 0,
						randomValidTime: this.randomValidTime,
						speedLimit: speedLimit_st + "-" + speedLimit_et,
						maleDayUpper: this.configForm.maleDayUpper * 1000,
						femaleDayUpper: this.configForm.femaleDayUpper * 1000,
						maleMinSingleDis: this.configForm.maleMinSingleDis * 1000,
						femaleMinSingleDis: this.configForm.femaleMinSingleDis * 1000
					})
				}).then(response => {
					if (response.data.error == 10000) {
						this.$util.successMsg("保存成功");
						location.href = "/#/sportConfig";
					} else {
						this.$util.errorMsg(response.data.message);
					}
				});
			},
			//获取校区
			getCampus() {
				let url = this.$util.domain + "/campusadminapi/v1/tools/campuszones";

				this.$http({
					url,
					method: "GET"
				}).then(response => {
					if (response.data.error == 10000) {
						let dataList = response.data.data;
						if (dataList && dataList.length > 0) {
							for (let i = 0; i < dataList.length; i++) {
								this.campusZones.push({
									unid: dataList[i].unid,
									name: dataList[i].zoneName
								});
							}
							this.configForm.campusZone = this.unid * 1;
						}
					}
				});
			},
			// 根据校区id获取配置详情
			getConfigDetail() {
				let url = this.$util.domain + "/managerapi/v1/sportconfig/detail";

				this.$http({
					url,
					method: "POST",
					body: JSON.stringify({
						unid: parseInt(this.unid)
					})
				}).then(response => {
					if (response.data.error == 10000) {
						let dataList = response.data.data;

						this.configForm = {
							maleDayUpper: dataList.maleDayUpper / 1000 + "",
							maleMinSingleDis: dataList.maleMinSingleDis / 1000 + "",
							femaleDayUpper: dataList.femaleDayUpper / 1000 + "",
							femaleMinSingleDis: dataList.femaleMinSingleDis / 1000 + "",
							campusZone: parseInt(this.unid)
						};
						let speedLimit_min = dataList.speedLimit.slice(0, dataList.speedLimit.indexOf("-")) * 1;
						let speedLimit_max = dataList.speedLimit.slice(dataList.speedLimit.indexOf("-") + 1) * 1;
						// parseInt
						this.configForm.speedLimit_min = parseInt(speedLimit_min) + "";
						this.configForm.speedLimit_minSec = parseInt((speedLimit_min - parseInt(speedLimit_min)) * 60) + "";
						this.configForm.speedLimit_max = parseInt(speedLimit_max) + "";
						this.configForm.speedLimit_maxSec = parseInt((speedLimit_max - parseInt(speedLimit_max)) * 60) + "";
						this.isFreedomRunCalculate = dataList.isFreedomRunCalculate == 0 ? false : true;
						this.randomValidTime = dataList.randomValidTime;
						this.sequenceRun = dataList.isSequence == 0 ? false : true;
						this.effectiveTime = dataList.randomValidTime.length > 0 ? true : false;
						if (this.randomValidTime.length > 0) {
							this.timeTags = this.randomValidTime.map((item) => {
								let now = new Date().format("yyyy/MM/dd");
								let start = new Date(now + " " + item.startTime).format("hh:mm");
								let end = new Date(now + " " + item.endTime).format("hh:mm");
								return start + "-" + end;
							});
						}
					}
				}, (response) => {
					this.$util.errorMsg(response.data.message);
				});
			},
			// 添加时间标签
			handleAddTime() {
				if (isNaN(this.time1) || isNaN(this.time2) || this.time1 == "" || this.time2 == "") {
					return;
				}
				let tagst = new Date(this.time1).format("hh:mm");
				let taget = new Date(this.time2).format("hh:mm");
				let ranst = new Date(this.time1).format("hh:mm:00");
				let ranet = new Date(this.time2).format("hh:mm:59");
				let now = new Date().format("yyyy/MM/dd");
				let sTime = new Date(now + " " + ranst).getTime();
				let eTime = new Date(now + " " + ranet).getTime();
				if (sTime >= eTime) {
					this.time1 = "";
					this.time2 = "";
					return;
				}
				if (this.timeTags.length < 1) {
					this.timeTags.push(tagst + "-" + taget);
					this.randomValidTime.push({ startTime: ranst, endTime: ranet });
					this.time1 = "";
					this.time2 = "";
				} else {
					for (let i = 0; i < this.timeTags.length; i++) {
						let nst = this.timeTags[i].split("-")[0];
						let net = this.timeTags[i].split("-")[1];
						let prest = new Date(now + " " + nst).getTime();
						let preet = new Date(now + " " + net).getTime();
						if (!(prest > eTime || preet < sTime)) {
							this.time1 = "";
							this.time2 = "";
							return;
						}
						if (i == this.timeTags.length - 1 && (prest > eTime || preet < sTime)) {
							this.timeTags.push(tagst + "-" + taget);
							this.randomValidTime.push({ startTime: ranst, endTime: ranet });
							this.time1 = "";
							this.time2 = "";
							return;
						}
					}
				}
			},
			// 删除时间标签
			handleClose(tag) {
				let nst = tag.split("-")[0];
				let now = new Date().format("yyyy/MM/dd");
				let nowTime = now + " " + nst;
				let newst = new Date(nowTime).format("hh:mm:00");
				this.randomValidTime = this.randomValidTime.filter(item => {
					return item.startTime != newst;
				});
				this.timeTags.splice(this.timeTags.indexOf(tag), 1);
			},
			cancel() {
				location.href = "/#/sportConfig";
			}
		}
	};
</script>

<style>
	#newConfig {
		padding-top: 80px;
		height: calc(100% - 100px);
	}

	#newConfig .title {
		color: #0398ff;
	}

	#newConfig .effect-time-tag {
		min-height: 120px;
		margin-top: 20px;
		width: 40%;
		padding: 5px;
		box-sizing: border-box;
		border: 1px solid gray;
	}

	.el-time-panel__btn.cancel {
		position: relative;
	}

	#newConfig .el-input1 {
		display: inline-block;
		width: 40%;
		margin-right: 5px;
	}

	#newConfig .peisu {
		width: 80px;
		display: inline-block;
	}
</style>